<template>
  <div class="permissions-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="hAdd(1,'0')">添加权限</el-button>
        </div>
        <el-table
          border
          :data="list"
          row-key="id"
        >
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <!-- type=1时是页面级权限 它可以继续做添加： 设置页面下边某个功能是否可以操作
								type=2时是按钮级别的访问权限 它就不能再继续细分了，它就没有添加了 -->
              <el-button
                v-if="row.type===1"
                type="text"
                @click="hAdd(2,row.id)"
              >添加</el-button>
              <el-button type="text" @click="hEdit(row.id)">编辑</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <!-- //弹层模块-->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      :title="isEdit? '编辑' : '添加'"
      @close="resetForm"
    >
      <!-- 表单内容 -->
      <el-form ref="refForm" :rules="rules" :model="formData" label-width="100px">
        <el-form-item label="权限名称">
          <el-input v-model="formData.name" prop="name" />
        </el-form-item>
        <el-form-item label="权限标识">
          <el-input v-model="formData.code" prop="code" />
        </el-form-item>
        <el-form-item label="权限描述">
          <el-input v-model="formData.description" prop="description" />
        </el-form-item>
        <el-form-item label="权限启用">
          <el-switch
            v-model="formData.enVisible"
            active-text="启用"
            active-value="1"
            inactive-text="不启用"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="text-align: right;">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script>
// 列表转化成树
import { tranListToTreeData } from '@/utils'
// 获取权限列表de api
import { getPermissionList, addPermission, delPermission, updatePermission, getPermissionDetail } from '@/api/permissions'
export default {
  data() {
    const validName = (rule, value, callback) => {
      // 如果是编辑需要排除自己
      let{ list } = this
      const { formData, isEdit } = this
      list = isEdit ? list.filter(item => item.id !== formData.id) : list
      list.filter(item => item.pid * 1 === formData.pid).some(it => it.name.trim() === value.trim())
        ? callback(new Error(value + '重复了'))
        : callback()
    }
    const validCode = (rule, value, callback) => {
      let { list } = this
      const { isEdit, formData } = this
      list = isEdit ? list.filter(it => it.id !== formData.id) : list
      list.map(it => it.code).includes(value)
        ? callback(new Error(value + '重复了'))
        : callback()
    }
    return {
      list: [], // 用来接收数据的
      showDialog: false, // 是否显示弹层
      isEdit: false,	//  isEdit来区别是否处于编辑状态
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },

      // 校验规则
      rules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入权限描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    async loadPermissionList() {
      try {
        // 调用接口获取数据
        const res = await getPermissionList()
        console.log('权限页面的表格数据', res)
        this.list = tranListToTreeData(res.data) // 保存数据
      } catch (err) {
        console.log('错误提示', err)
      }
    },
    // 删除功能
    async doDel(id) {
      try {
        const res = await delPermission(id)
        console.log(res)

        this.loadPermissionList()
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 用户点击删除
    hDel(id) {
    // alert(id)
      this.$confirm('你确定要删除吗？').then(() => {
        this.doDel(id)
      }).catch(() => {

      })
    },
    // 添加按钮
    hAdd(type, id) {
      this.showDialog = true
      // 记录当前添加的关键信息
      this.formData.type = type
      this.formData.pid = id
      this.isEdit = false
    },
    // 添加
    async doAdd() {
      try {
        const res = await addPermission(this.formData)
        console.log(res)
        // 关闭弹出层
        this.showDialog = false
        // 重新发请求
        this.loadPermissionList()
        this.$message.success('添加成功')
      } catch (err) {
        console.log('错误提示', err)
      }
    },
    // 编辑
    async hEdit(id) {
      this.isEdit = true
      // 1. 根据id去获取详情
      const res = await getPermissionDetail(id)
      console.log('权限点详情：', res)
      // 2. 填充在表单中
      this.formData = res.data
      // 3.显示弹层
      this.showDialog = true
    },
    // 用户点击了编辑按钮
    async doEdit() {
      try {
        const res = await updatePermission(this.formData)
        console.log(res)

        this.showDialog = false
        this.loadPermissionList()
        this.$message.success('修改成功')
      } catch (err) {
        console.log(err)
        this.$message.error('修改失败')
      }
    },
    // 确定按钮
    hSubmit() {
      this.$refs.refForm.validate(valid => {
        // 做添加或编辑
        valid && this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 当弹层关闭时，重置表单
    resetForm() {
      // 把数据清空
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      // 清空内容
      this.$refs.refForm.resetFields()
    }

  }
}

</script>
<style lang="less" scoped>

</style>
